<template >
  <div>
    <el-button type="primary" @click="AddRole">添加</el-button>

    <template>
      <el-table :data="rolelist" border style="width: 100%">
        <el-table-column prop="roleName" label="角色"> </el-table-column>
        <el-table-column prop="enable" label="状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.enable == false">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" v-if="scope.row.enable == false" @click="DelRole(scope.row.id)">禁用</el-button>
            <el-button type="success" v-else @click="DelRole(scope.row.id)">启用</el-button>
            <el-button type="primary" @click="AddPei(scope.row.id)" @change="SetNodeChecked()">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="form.RoleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-if="updateble == false" @click="submitForm('ruleForm')">添加角色</el-button>
          <el-button type="primary" v-else @click="submitForms('ruleForm')">修改角色</el-button>
          <el-button @click="jump()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="dialogFormVisible1">
      <!-- 接受Tree页面 -->
      <div id="areaTree">
        <div class="box-title">
          <a href="#">列表<i class="fa fa-refresh"></i></a>
        </div>
        <div class="tree-box">
          <div class="zTreeDemoBackground left">
            <ul id="treeDemo" class="ztree"></ul>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="AddRolePermission">确 定</el-button>
        <!-- <el-button type="primary" @click="SetNodeChecked">反填
                </el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  GetRoleDtoAsyne,
  AddRoleAsyne,
  DelRoleDtoAsyne,
  RackRoleDto,
  UpdRoleAsync,
  GetRoleMoent,
  AddRolePermissionapi,
  SelRolePermissionAsync,
} from "@/api/systemSet/role";
export default {
  data() {
    return {
      form: {
        id: "",
        RoleName: "",
        Enable: "",
        CreateTime: "",
      },
      form: {
        RoleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      serData: {
        name: "",
      },
      //角色列表
      rolelist: [],
      //添加弹出层是否开启
      dialogFormVisible: false,
      dialogFormVisible1: false,
      updateble: false,
      setting: {
        view: {
          showLine: true,
        },
        check: {
          enable: true, //显示复选框
          chkStyle: "checkbox",
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "value",
            pIdKey: "pid",
            rootPId: 0,
          },
        },
        callback: {
          onCheck: this.handleCheck,
        },
      },
      zTree: [],
      RId: "",
      checkedValue: {},
      RolePermission: [],
    };
  },
  methods: {
    //反填权限
    SelRolePermission(val) {
      let myparams = {
        RoleId: val,
      };
      console.log(myparams);
      SelRolePermissionAsync(myparams).then((res) => {
        console.log(res.data);
        this.RolePermission = res.data;
        console.log(this.RolePermission);
      });
    },
    //添加角色权限
    AddRolePermission() {
      // let zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
      // let checkedNodes = zTreeObj.getCheckedNodes(true);
      // let checkedValues = checkedNodes.map(node => node.value);
      // console.log(this.checkedValues);
      var myparams = {
        RoleID: this.RId,
        PermissionsID: this.checkedValue,
      };
      //console.log(myparams);
      AddRolePermissionapi(myparams).then((res) => {
        if (res.data.totalCount > 0) {
          this.$message({
            message: "分配成功",
            type: "success",
          });
          this.dialogFormVisible1 = false;
        } else {
          this.$message({
            message: "分配失败",
            type: "error",
          });
        }
      });
    },
    AddPei(val) {
      this.dialogFormVisible1 = true;
      this.SelRolePermission(val);
      this.treeDemos();
      this.RId = val;
      //console.log(this.RId);
      return;
    },
    treeDemos() {
      GetRoleMoent().then(
        (res) => {
          this.zTree = res.data;
          //console.log(this.zTree);
          // 初始化ztree
          var treeObj = $.fn.zTree.init(
            $("#treeDemo"),
            this.setting,
            this.zTree
          );

          for (var i = 0; i < this.RolePermission.length; i++) {
            var node = treeObj.getNodeByParam("value", this.RolePermission[i]);

            treeObj.checkNode(node, true, true); //将指定ID的节点设置为选中
            //treeObj.expandNode(node, true, false);//将指定ID节点展开

            //重新渲染数据节点，否则不显示勾选。设置checked属性之后，一定要更新该节点，否则会出现只有鼠标滑过的时候节点才被选中
            treeObj.updateNode(node, true);

            //刷新整个zTree
            //var treeObj = $.fn.zTree.getZTreeObj("tree");
            //treeObj.refresh();
          }
        },
        (err) => {
          console.error(err);
        }
      );
    },
    handleCheck() {
      let zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
      let checkedNodes = zTreeObj.getCheckedNodes(true);
      let checkedValues = checkedNodes.map((node) => node.value);
      this.checkedValue = checkedValues.map((value) => String(value)).join(",");

      //console.log(checkedValues);
    },
    //角色反填
    //EditRole(val) {},
    Rcak(val) {
      let myparams = {
        id: val,
      };
      RackRoleDto(myparams).then((res) => {
        // console.log(res.data.data.name);
        this.form.Id = res.data.data.id;
        this.form.RoleName = res.data.data.roleName;
        this.form.Enable = res.data.data.isDelete;
        this.form.CreateTime = res.data.data.createTime.substring(0, 10);
      });
    },
    //修改角色
    submitForms(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Upd();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    Upd() {
      var myparams = {
        Id: this.form.id,
        RoleName: this.form.roleName,
        Enable: this.form.isDelete,
        CreateTime: this.form.createTime,
      };
      console.log(myparams);
      UpdRoleAsync(myparams).then((res) => {
        if (res.data.totalCount > 0) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.gerrole();
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
    //修改角色状态
    DelRole(val) {
      this.$confirm("您确定要操作吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(val);
          this.Del(val);
          //刷新页面
          this.gerrole();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    Del(val) {
      let myparams = {
        id: val,
      };

      DelRoleDtoAsyne(myparams).then((res) => {
        //  console.log(res);
        if (res.data.totalCount > 0) {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.gerrole();
        } else {
          this.$message({
            type: "success",
            message: "操作失败!",
          });
        }
      });
    },
    //添加角色
    AddRole() {
      this.form.RoleName = "";
      this.dialogFormVisible = true;
      this.updateble = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Add();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    Add() {
      AddRoleAsyne(this.form).then((res) => {
        if (res.data.totalCount > 0) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.gerrole();
        }
      });
    },
    //角色列表
    gerrole() {
      let myparams = {
        name: this.serData.name,
      };

      GetRoleDtoAsyne(myparams).then(
        (res) => {
          this.rolelist = res.data.data;
          //console.log(res.data.data);
        },
        (err) => {
          console.error(err);
        }
      );
    },
    jump(){
      this.dialogFormVisible=false;
    }
  },
  mounted() {
    this.gerrole();
    //this.SelRolePermission();
  },
  created() { },
};
</script>
<style >
#areaTree {
  border: 1px solid #e5e5e5;
  margin-bottom: 2px;
  border-radius: 4px;
  overflow: hidden;
  width: 50%;
}

.box-title {
  border-radius: 3px 3px 0 0;
  background-color: #f5f5f5;
}

.box-title a {
  color: #2fa4e7;
  text-decoration: none;
  font-size: 14px;
  display: block;
  padding: 8px 15px;
  cursor: pointer;
}

.box-title .fa {
  float: right;
  line-height: 20px;
}
</style>